package com.example.androiddemo.contentproviderdemo;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androiddemo.R;

import java.util.ArrayList;
import java.util.List;

public class ContentProviderMainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mGetContacts;
    private TextView mShowContacts;
    private List<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contentprovider_main);

        mGetContacts = findViewById(R.id.getContacts);
        mShowContacts = findViewById(R.id.showContacts);
        list = new ArrayList<>();

        mGetContacts.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getContacts:
                list.clear();
                ContentResolver resolver = getContentResolver();
                Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null,
                        null, null, null);
                while (cursor.moveToNext()) {
                    String ID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); //获取id
                    String Name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));//获取姓名
                    list.add("姓名：" + Name);

                    //one person have multiple numbers, so you have to use query() method to query all numbers of one person.
                    Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone._ID + "=" + ID, null, null);
                    while (phoneCursor.moveToNext()) {
                        String Number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        list.add("\n联系电话：" + Number);
                    }
                    list.add("\n");
                }
                mShowContacts.setText("");
                for (int i = 0; i < list.size(); i++) {
                    mShowContacts.append(list.get(i));
                }
                break;
            default:
                break;

        }
    }
}